
<template>
  <transition name="fade">
    <div class="masker" @click.stop="$emit('closeVisible', $event,false),resetData()" v-show="visible">
      <div class="contant_wrap" @click.stop="$emit('closeVisible', $event,false),resetData()">
        <transition name="slidetogle">
          <div class="content_slide" @click.stop v-show="visible">
            <transition name="updownanimate">
              <div class="">
                <div class="cunstom_wrap">
                  <div class="cunstom_header" @click.stop>
                    <p>{{ currentItemProps.officeTitle || '暂无' }}</p>
                    <span class="appIcon-iconfont appIcon-guanbijianli pointer"
                      @click.stop="$emit('closeVisible', $event,false),resetData()"></span>
                  </div>
                  <transition name="selected_user">
                    <div class="headportrait" v-show="selectedMemerList.length > 0">
                      <!-- :class="{ h190: isSpread && visible, h70: !isSpread && visible }" -->
                      <!-- ,h140:selectedMemerList.value.length > 12 -->
                      <ul class="" :class="{ h190: isSpread, h70: !isSpread}">
                        <li @click.stop="selectedDelete(item, index)" v-for="(item, index) in selectedMemerList"
                          :key="index">
                          <img class="select_member" :src="item.userAvatar" alt="" />
                          <span class="appIcon-iconfont appIcon-shanjianrenyuan delete_icon"></span>
                        </li>
                      </ul>
                      <span v-if="selectedMemerList.length > 6"
                        class="appIcon-iconfont appIcon-chevron-down toggle_slide" :class="{ rotate180: isSpread }"
                        @click.stop="toggleSlides"></span>
                    </div>
                  </transition>
                </div>
                <div class="search">
                  <p class="input_wrap">
                    <input type="text" @focus.stop @click.stop placeholder="请输入共享人" v-model.trim="nickName">
                    <i class="appIcon-iconfont appIcon-sousuo pointer serch_icon"></i>
                    <i v-if="nickName.length > 0" class="appIcon-iconfont appIcon-guanbijianli pointer clear_icon"
                      @click.stop="clearWords"></i>
                  </p>
                </div>
              </div>
            </transition>
            <div class="xr-list-outBox">
              <ul ref="scrollListRef" class="xr-list">
                <li class="xr-list-item" v-for="(item, index) in pageMemberList" :key="index"
                  @click.stop="$emit('rowClick', item), addMember(item)">
                  <slot :item="item" :index="index">
                    <div class="list_item">
                      <p class="avantar_title">
                        <img class="avantar" v-lazy="item.userAvatar" alt="" />
                        <span>{{ item.nickName }}</span>
                      </p>
                      <p>
                        <span v-if="item.selected" class="appIcon-iconfont appIcon-xuanzhongmoren tc_7a84ff"></span>
                        <span v-else class="appIcon-iconfont appIcon-weixuanbeifen tc_7a84ff"></span>
                      </p>
                    </div>
                  </slot>
                </li>
              </ul>

            </div>
            <div class="sure_btn_wrap">
              <span v-if="props.comefrom === 'home' && selectedMemerList.length == 0"></span>
              <p class="sure_btn" v-else @click.stop="sureChangeMember">确认共享</p>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </transition>

</template>

<script lang="ts" setup>
import { withDefaults, ref, onMounted, computed, reactive, watch ,onBeforeUnmount} from "vue";
import { useMainStore} from '@/store'
import { storeToRefs } from 'pinia'
import { doStoreShareMember } from "@/api/share";
import { getUserPageList } from "@/api/user";
const mainStore = useMainStore()
const emits = defineEmits(["closeVisible", 'rowClick', 'memberUpdate']);
const props = defineProps(['visible', 'currentItemProps','comefrom','curretUserId'])
const pageMemberList = ref([])
const selectedMemerList = ref([])
const outHeight = ref(0);
const nickName = ref('')
const scrollLoad =ref(false)
const { currentLogUserId } = storeToRefs(mainStore)
// 定义分页参数
const page = reactive({
  current: 1,
  size: 20,
  memberTotal:0,
  totalPage:0
})

const scrollListRef: any = ref(null)

const memberLoadScroll = () => {
  if(scrollListRef.value.scrollHeight - scrollListRef.value.clientHeight < scrollListRef.value.scrollTop + 5) {
    if(page.current < page.totalPage) {
      // console.log(" 到底啦" + '===')
      scrollLoad.value = true
      page.current ++
      getAllUserList()
    }
  }
}
onMounted(() => {
  let allLi = document.querySelectorAll(".xr-list-item");
  allLi.forEach((item: any) => {
    outHeight.value += item.offsetHeight
  });
  outHeight.value += 10
  scrollListRef.value.addEventListener('scroll',memberLoadScroll , false)
})
onBeforeUnmount(() => {
  scrollListRef.value.removeEventListener('scroll',memberLoadScroll,false)
})
const isSpread = ref(false)
const toggleSlides = () => {
  isSpread.value = !isSpread.value
}
const clearWords = () => {
  nickName.value = ''
  pageMemberList.value = []
  page.current  = 1
}
watch(
  props,
  () => {
    if (props.visible) {
      nickName.value = ''
      if (props.currentItemProps.ownerSharerList != null) {
        // let selectedArr = props.currentItemProps.ownerSharerList
        // selectedMemerList.value = JSON.parse(JSON.stringify(props.currentItemProps.ownerSharerList)) 
        selectedMemerList.value = JSON.parse(JSON.stringify(props.currentItemProps.ownerSharerList)) 
      } else {
        selectedMemerList.value = []
        // pageMemberList.value = infoData.allMemberList
      }
      pageMemberList.value = []
      page.current  = 1
      isSpread.value = false
      
      
      getAllUserList()
      // if (props.currentItemProps.ownerSharerList != null) {
      //   selectedMemerList.value = JSON.parse(JSON.stringify(props.currentItemProps.ownerSharerList)) 
      //   pageMemberList.value.forEach((member: any) => {
      //     selectedMemerList.value.forEach((item: any) => {
      //       if (item.userId == member.hhxsUserId) {
      //         member.selected = true
      //       }
      //     })
      //   })
      //   infoData.allMemberList = pageMemberList.value
      // } else {
      //   selectedMemerList.value = []
      //   pageMemberList.value = infoData.allMemberList
      // }
    }
  },

)
watch(
  nickName,
  (newVal) => {
    // if (newVal) {
      // console.log(111, selectedMemerList.value);
      scrollLoad.value = false
      pageMemberList.value = []
      // console.log(222, selectedMemerList.value);
      page.current  = 1
      getAllUserList()
  },
  // { deep: true, immediate: true }
);

const resetData = () => {
  setTimeout(() => {
    page.current  = 1
    nickName.value = ''
    pageMemberList.value = []
  },400)
}
const selectedDelete = (itemInfo: any, index: any) => {
  selectedMemerList.value.splice(index, 1)
  pageMemberList.value.forEach((item: any) => {
    if (itemInfo.userId  == item.hhxsUserId || itemInfo.hhxsUserId == item.hhxsUserId) {
      item.selected = false
    }
  })
}
const addMember = (item: any) => {
  // let pushedMember = JSON.parse(JSON.stringify(pageMemberList.value.filter((item:any) => {return item.selected})))
  if(item.selected) {
    item.selected = false
    let indexPos = null
    selectedMemerList.value.forEach((val:any,pos:any) => {
      if(item.hhxsUserId == val.hhxsUserId || item.hhxsUserId == val.userId) {
        indexPos = pos
        // console.log('indexPos',indexPos);
        
      }
    })
    selectedMemerList.value.splice(indexPos, 1)
  }else {
    item.selected = true
    let itemObj = JSON.parse(JSON.stringify(item))
    selectedMemerList.value.push(...[itemObj])
  }
  if (selectedMemerList.value.length > 6) {
    isSpread.value =true
  }
}


const sureChangeMember = () => {
  if (props.comefrom === 'home' && !selectedMemerList.value.length) {
    return false
  }
  storeShareMember()
}

// 获取所有用户列表
const getAllUserList = () => {
  let params = {
    nickName: nickName.value,
    size: page.size,
    current: page.current,
  }
  getUserPageList(params).then((res: any) => {
    // console.log(66666,res);
    page.totalPage = res.data.data.pages
    page.memberTotal = res.data.data.total
    res.data.data.records.forEach((item: any) => {
      item.selected = false
    })
    // let baseData = currentLogUserId.value ? res.data.data.records.filter((item:any) => {return item.hhxsUserId != currentLogUserId.value}) : res.data.data.records
    let baseData =  res.data.data.records
    // console.log('baseData',selectedMemerList.value);
    if(scrollLoad.value) {
      pageMemberList.value.push(...baseData) 

    }else {
      pageMemberList.value = baseData
    }

    pageMemberList.value = currentLogUserId.value ? pageMemberList.value.filter((item:any) => {return item.hhxsUserId != currentLogUserId.value}) : pageMemberList.value
    // console.log('pageMemberList',pageMemberList.value);
    // console.log('infoData.allMemberList',infoData.allMemberList);
    if(selectedMemerList.value.length){
      // console.log('selectedMemerList 有成员');
      
      pageMemberList.value.forEach((member: any) => {
        selectedMemerList.value.forEach((item: any) => {
          if (item.userId == member.hhxsUserId) {
            member.selected = true
          }
        })
      })
    }
    pageMemberList.value = Array.from(new Set(pageMemberList.value))
    // console.log('pageMemberList==',pageMemberList.value);
    // pageMemberList.value = JSON.parse(JSON.stringify(infoData.allMemberList))

    // if (props.currentItemProps.ownerSharerList != null) {
    //   let selectedArr = props.currentItemProps.ownerSharerList
    //   // selectedMemerList.value = JSON.parse(JSON.stringify(props.currentItemProps.ownerSharerList)) 
    //   selectedMemerList.value = selectedMemerList.value.concat(selectedArr)
    //   pageMemberList.value.forEach((member: any) => {
    //     selectedMemerList.value.forEach((item: any) => {
    //       if (item.userId == member.hhxsUserId) {
    //         member.selected = true
    //       }
    //     })
    //   })
    //   // infoData.allMemberList = pageMemberList.value
    // } else {
    //   // selectedMemerList.value = []
    //   // pageMemberList.value = infoData.allMemberList
    // }
  })
}

// 存储分享成员   删除或添加
const storeShareMember = () => {
  let params = {
    officeId: props.currentItemProps.officeId,
    operationType: 3, //操作类型：1：添加拥有者；2：删除拥有者；3:替换拥有者	
    ownerList: selectedMemerList.value.map((val: any) => { return val.hhxsUserId || val.userId})
  }
  doStoreShareMember(params).then((res: any) => {
    // selectedMemerList.value = infoData.allMemberList.filter((item: any) => { return item.selected })
    // pageMemberList.value.forEach((item:any) => {
    //   item.selected = false
    // })
    emits('closeVisible', true,true)
  })
}
</script>

<style scoped lang="scss">
@import './styles.scss';
</style>